package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.stock.service.IStockService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/base/stock")
@Api(tags = "库存模块")
public class StockController {

    @Autowired
    private IStockService stockService;
    @PostMapping("reduce/count")
    @ApiOperation("商品库存减少")

    //标记当前控制层方法被Sentinel管理限流
    //blockHandler当请求被限流时 运行哪个方法
    @SentinelResource(value = "reduceCommodityCount",blockHandler = "blockError",fallback = "fallbackError")
    public JsonResult reduceCommodityCount(StockReduceCountDTO stockReduceCountDTO){
        stockService.reduceCommodityCount(stockReduceCountDTO);

        if(Math.random()>0.5){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"随机异常");
        }

        return JsonResult.ok("商品减少库存完成!!");
    }
    //Sentinel规定限流响应方法有如下要求
    //1.必须是public的方法
    //2.返回值类型必须和控制器方法一致
    //3.参数必须和控制器方法一样的前提下,在参数列表最后添加一个BlockException
    //4.方法名必须和上面的blockHandler指定的一样
    public  JsonResult blockError(StockReduceCountDTO stockReduceCountDTO, BlockException e){
        return JsonResult.failed(ResponseCode.BAD_REQUEST,"服务器繁忙,请稍后");

    }
    //当控制器方法运行发生异常时,Sentinel支持服务降级
    //我们可以在这个方法中对用户的请求进行一些补救
    //方法格式跟限流方法一致,只是不必须添加BlockException参数
    public JsonResult fallbackError(StockReduceCountDTO stockReduceCountDTO){

        return  JsonResult.failed(ResponseCode.BAD_REQUEST,"库存修改失败,可降级");

    }
}
